package com.sduept.nwld.dataserver.controller.fault;

import com.sduept.bigdata.fault.entity.FaultRecord;
import com.sduept.bigdata.fault.manager.FaultEditLockManager;
import com.sduept.bigdata.fault.manager.FaultEditLockManager.LockData;
import com.sduept.bigdata.fault.manager.FaultRecordQueryManager;
import com.sduept.bigdata.web.jsf.controller.AbstractController;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import javax.inject.Named;
import javax.faces.view.ViewScoped;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Named
@ViewScoped
public class FaultEditLockedInfoController extends AbstractController{

	private static final long serialVersionUID = -2776100189041891574L;

	@Autowired
	private FaultEditLockManager lockManager;
	@Autowired
	private FaultRecordQueryManager queryManager;
	
	private List<FaultEditDTO> lockedFaults = new ArrayList<>();
	
	@PostConstruct
	public void init() {
		Map<String, LockData> map = lockManager.getLockMap();
		if(map == null) {
			return;
		}
		lockedFaults.clear();
		for(Map.Entry<String, LockData> en:map.entrySet()) {
			if(StringUtils.isEmpty(en.getKey())) {
				continue;
			}
			FaultRecord f = queryManager.findById(en.getKey());
			if(f != null ) {
				lockedFaults.add(new FaultEditDTO(f, en.getValue()));
			}
		}
	}
	
	public void delocking(FaultRecord fault) {
		Map<String, LockData> map = lockManager.getLockMap();
		if(map != null && map.containsKey(fault.getId())) {
			lockManager.getLockMap().remove(fault.getId());
		}
		for(FaultEditDTO d:lockedFaults) {
			if(d.getFault().getId().equals(fault.getId())) {
				lockedFaults.remove(d);
				break;
			}
		}
	}
	
	public class FaultEditDTO {
		private FaultRecord fault;
		private LockData lockData;
		
		public FaultEditDTO(FaultRecord fault,LockData lockData) {
			this.fault = fault;
			this.lockData = lockData;
		}

		public FaultRecord getFault() {
			return fault;
		}

		public void setFault(FaultRecord fault) {
			this.fault = fault;
		}

		public LockData getLockData() {
			return lockData;
		}

		public void setLockData(LockData lockData) {
			this.lockData = lockData;
		}
		
	}

	public List<FaultEditDTO> getLockedFaults() {
		return lockedFaults;
	}

	public void setLockedFaults(List<FaultEditDTO> lockedFaults) {
		this.lockedFaults = lockedFaults;
	}
	
	
}
